package com.aiti.lulian.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.entity.crad.LuLianEnterpriseOperation;
import com.aiti.lulian.gxmh.entity.GxmhEnterpriseLinkCount;
import com.aiti.lulian.mapper.card.LuLianEnterpriseOperationMapper;
import com.aiti.lulian.mapper.gxmh.GxmhEnterpriseLinkCountMapper;
import com.aiti.lulian.service.ILuLianEnterpriseOperationService;
import com.aiti.lulian.service.ILuLianEnterpriseService;
import com.aiti.lulian.vo.LuLianEnterpriseOperationVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class LuLianEnterpriseOperationServiceImpl extends BaseSerivceImpl<LuLianEnterpriseOperationMapper, LuLianEnterpriseOperation> implements ILuLianEnterpriseOperationService {

    private final LuLianEnterpriseOperationMapper luLianEnterpriseOperationMapper;

    private final ILuLianEnterpriseService luLianEnterpriseService;

    private GxmhEnterpriseLinkCountMapper gxmhEnterpriseLinkCountMapper;

    @Value("${operation-center.highest-privilege-users}")
    private String highestPrivilegeUsers;

    public LuLianEnterpriseOperationServiceImpl(LuLianEnterpriseOperationMapper luLianEnterpriseOperationMapper, ILuLianEnterpriseService luLianEnterpriseService, GxmhEnterpriseLinkCountMapper gxmhEnterpriseLinkCountMapper) {
        this.luLianEnterpriseOperationMapper = luLianEnterpriseOperationMapper;
        this.luLianEnterpriseService = luLianEnterpriseService;
        this.gxmhEnterpriseLinkCountMapper = gxmhEnterpriseLinkCountMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdateEnterpriseOperation(LuLianEnterpriseOperation luLianEnterpriseOperation) {
        String enterpriseId = luLianEnterpriseOperation.getEnterpriseId();
        LuLianEnterpriseOperation obj = luLianEnterpriseOperationMapper.selectOne(new LambdaQueryWrapper<LuLianEnterpriseOperation>().eq(LuLianEnterpriseOperation::getEnterpriseId, enterpriseId));
        int rows;
        if (obj == null) {
            //新增记录
            rows = luLianEnterpriseOperationMapper.insert(luLianEnterpriseOperation);
        } else {
            //更新记录
            luLianEnterpriseOperation.setUpdateBy(luLianEnterpriseOperation.getCreator());
            luLianEnterpriseOperation.setCreator(null);
            rows = luLianEnterpriseOperationMapper.update(luLianEnterpriseOperation, new LambdaUpdateWrapper<LuLianEnterpriseOperation>().eq(LuLianEnterpriseOperation::getEnterpriseId, obj.getEnterpriseId()));
        }
        if (StrUtil.isNotBlank(luLianEnterpriseOperation.getQualificationRecognitionType())) {
            LambdaUpdateWrapper<LuLianEnterprise> updateWrapper = new LambdaUpdateWrapper<LuLianEnterprise>().eq(LuLianEnterprise::getBaseId, enterpriseId);
            if (StrUtil.equals(luLianEnterpriseOperation.getQualificationRecognitionType(), "1")) {
                // “山东制造·云上展厅”资质认定
                updateWrapper.set(LuLianEnterprise::getSdzzYszt, true);
                updateWrapper.set(LuLianEnterprise::getSdzzPprd, false);
            } else if (StrUtil.equals(luLianEnterpriseOperation.getQualificationRecognitionType(), "2")){
                // “山东制造·品牌认定”资质认定
                updateWrapper.set(LuLianEnterprise::getSdzzPprd, true);
                updateWrapper.set(LuLianEnterprise::getSdzzYszt, false);
            }
            luLianEnterpriseService.update(updateWrapper);
        }
        // 更新过期时间和版本
        if(luLianEnterpriseOperation.getMiniProgramVersion() != null) {
            luLianEnterpriseOperationMapper.updateEnterpriseMiniVersion(enterpriseId, luLianEnterpriseOperation.getMiniProgramVersion());
            this.dealUserRoleAndCompanyId(luLianEnterpriseOperation.getMainUserId(), enterpriseId);
        }
        if(StrUtil.isNotEmpty(luLianEnterpriseOperation.getExpirationTime())) {
            String expirationTime = luLianEnterpriseOperation.getExpirationTime() + " 23:59:59";
            luLianEnterpriseOperationMapper.updateEnterpriseExpirationTime(enterpriseId, expirationTime);
        } else {
            luLianEnterpriseOperationMapper.updateEnterpriseExpirationTime(enterpriseId, null);
        }
        // 如果MiniProgramVersion = 5，表示设置的版本是拓客版，需要在工信门户更新或新建拓客次数
        if(luLianEnterpriseOperation.getMiniProgramVersion() != null && luLianEnterpriseOperation.getMiniProgramVersion() == 5 && luLianEnterpriseOperation.getGxmhLinkCount() != null) {
            this.setGxmhLinkCount(luLianEnterpriseOperation, enterpriseId);
        }
    }

    // 设置工信门户解锁联系人次数
    private void setGxmhLinkCount(LuLianEnterpriseOperation luLianEnterpriseOperation, String enterpriseId) {
        GxmhEnterpriseLinkCount gxmhEnterpriseLinkCount = gxmhEnterpriseLinkCountMapper.queryEnterpriseLinkCount(enterpriseId);
        if(gxmhEnterpriseLinkCount == null) {
            gxmhEnterpriseLinkCount = new GxmhEnterpriseLinkCount();
            gxmhEnterpriseLinkCount.setBaseId(IdUtil.simpleUUID());
            gxmhEnterpriseLinkCount.setEnterpriseId(enterpriseId);
            gxmhEnterpriseLinkCount.setLinkCount(luLianEnterpriseOperation.getGxmhLinkCount());
            gxmhEnterpriseLinkCount.setBaseCreateTime(new Date());
            gxmhEnterpriseLinkCountMapper.insert(gxmhEnterpriseLinkCount);
        }else {
            gxmhEnterpriseLinkCount.setLinkCount(luLianEnterpriseOperation.getGxmhLinkCount());
            gxmhEnterpriseLinkCountMapper.updateById(gxmhEnterpriseLinkCount);
        }
    }

    /**
     * 处理用户角色和企业id
     * 如果用户id不为空则检查用户是否有企业管理员的角色，043ea2e3e02c4aa591df1f83e65069bc，
     * 如果没有则添加这个角色，再判断用户的用户表中company_id是否为空，为空则设置上企业id
     * 如果用户id为空，则在shou_enterprise_user表中查这个企业有多少用户，如果这个企业有多个用户则报错提示人工处理
     * 如果用户有一个则重复第一个步骤
     * @param mainUserId
     * @param enterpriseId
     */
    private void dealUserRoleAndCompanyId(String mainUserId, String enterpriseId) {
        if(StrUtil.isNotEmpty(mainUserId)) {
            this.delUserData(mainUserId, enterpriseId);
        }
        else {
            List<LuLianEnterpriseUser> luLianEnterpriseUsers = luLianEnterpriseOperationMapper.selectEnterpriseUserList(enterpriseId);
            if(CollectionUtil.isEmpty(luLianEnterpriseUsers)) {
                throw new BusinessException("该企业没有用户，无法设置用户企业管理员角色");
            }
            if(luLianEnterpriseUsers.size() > 1) {
                throw new BusinessException("该企业有多个用户，无法区分哪个用户是主账号，无法设置用户企业管理员角色。请联系相关人员手工处理");
            }
            LuLianEnterpriseUser luLianEnterpriseUser = luLianEnterpriseUsers.get(0);
            this.delUserData(luLianEnterpriseUser.getUserId(), enterpriseId);
        }
    }

    private void delUserData(String mainUserId, String enterpriseId) {
        Integer userRoleCount = luLianEnterpriseOperationMapper.selectUserEnterpriseManagerRoleCount(mainUserId);
        if(userRoleCount == 0) {
            luLianEnterpriseOperationMapper.insertEnterpriseManageRole(IdUtil.fastUUID(), mainUserId);
        }
        String companyId = luLianEnterpriseOperationMapper.queryCompanyIdByUserId(mainUserId);
        if(StrUtil.isEmpty(companyId)) {
            luLianEnterpriseOperationMapper.updateCompanyIdByUserId(enterpriseId, mainUserId);
        }
    }

    @Override
    public Message getEnterpriseOperationDetails(String enterpriseId) {
        LuLianEnterpriseOperationVo operationVo = luLianEnterpriseOperationMapper.selectEnterpriseOperationDetails(enterpriseId);
        GxmhEnterpriseLinkCount gxmhEnterpriseLinkCount = gxmhEnterpriseLinkCountMapper.queryEnterpriseLinkCount(enterpriseId);
        if(gxmhEnterpriseLinkCount != null) {
            operationVo.setGxmhLinkCount(gxmhEnterpriseLinkCount.getLinkCount());
        }
        return Message.success(operationVo);
    }

    @Override
    public Message getData() {
        Map<String, Object> resultMap = luLianEnterpriseOperationMapper.selectData();

        //格式化比值
        String activeRate = (String) resultMap.get("activeRate");
        String breakRate = (String) resultMap.get("breakRate");
        if (StrUtil.equals(activeRate, "100.00%")) {
            resultMap.put("activeRate", "100%");
        } else if (StrUtil.equals(activeRate, "0.00%")) {
            resultMap.put("activeRate", "0%");
        }
        if (StrUtil.equals(breakRate, "100.00%")) {
            resultMap.put("breakRate", "100%");
        } else if (StrUtil.equals(breakRate, "0.00%")) {
            resultMap.put("breakRate", "0%");
        }

        // 补充两个 转发次数和访问次数的总和
        Long pubCount = 0L;
        Long viewCount = 0L;
        LuLianEnterpriseOperationVo pubAndViewCountVo = luLianEnterpriseOperationMapper.selectPubAndViewCount();
        if(pubAndViewCountVo != null) {
            pubCount = pubAndViewCountVo.getPubCount();
            viewCount = pubAndViewCountVo.getViewCount();
        }
        resultMap.put("pubCount", pubCount);
        resultMap.put("viewCount", viewCount);

        // 每日新增企业数
        Date yesterdayDate = DateUtil.offsetDay(new Date(), -1);
        Integer newAddEnterpriseCount = luLianEnterpriseOperationMapper.selectNewAddEnterpriseCount(this.getYesterdayStartTime(yesterdayDate), this.getYesterdayEndTime(yesterdayDate));
        resultMap.put("newAddEnterpriseCount", newAddEnterpriseCount);
        // 开通企业用户总数
        Integer enterpriseUserCount = luLianEnterpriseOperationMapper.selectEnterpriseUserCount();
        resultMap.put("enterpriseUserCount", enterpriseUserCount);
        // 新开通企业用户数
        Integer enterpriseUserCountNew = luLianEnterpriseOperationMapper.selectEnterpriseUserCountNew(this.getYesterdayStartTime(yesterdayDate), this.getYesterdayEndTime(yesterdayDate));
        resultMap.put("enterpriseUserCountNew", enterpriseUserCountNew);
        return Message.success(resultMap);
    }

    private String getYesterdayStartTime(Date yesterdayDate) {
        return DateUtil.format(DateUtil.beginOfDay(yesterdayDate), "yyyy-MM-dd HH:mm:ss");
    }

    private String getYesterdayEndTime(Date yesterdayDate) {
        return DateUtil.format(DateUtil.endOfDay(yesterdayDate), "yyyy-MM-dd HH:mm:ss");
    }
}